package org.jeecg.modules.userReports.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import net.sf.saxon.expr.instruct.ForEach;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.aspectj.weaver.ast.Var;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.reportCronJobData.entity.ReportCronJobData;
import org.jeecg.modules.userReports.entity.UserReports;
import org.jeecg.modules.userReports.entity.UserReportsField;
import org.jeecg.modules.userReports.entity.UserReportsRow;
import org.jeecg.modules.userReports.vo.BuildReport;
import org.jeecg.modules.userReports.vo.BuildReportParam;
import org.jeecg.modules.userReports.vo.UserReportsPage;
import org.jeecg.modules.util.HttpClientUtil;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.userReports.service.IUserReportsService;
import org.jeecg.modules.userReports.service.IUserReportsFieldService;
import org.jeecg.modules.userReports.service.IUserReportsRowService;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;


/**
 * @Description: user_reports
 * @Author: jeecg-boot
 * @Date: 2023-02-25
 * @Version: V1.0
 */
@Api(tags = "user_reports")
@RestController
@RequestMapping("/userReports/userReports")
@Slf4j
public class UserReportsController {
    @Autowired
    private IUserReportsService userReportsService;
    @Autowired
    private IUserReportsFieldService userReportsFieldService;
    @Autowired
    private IUserReportsRowService userReportsRowService;

    @Value("${zfservice.url}")
    private String zfserviceUrl;

    @Value("${report-tmp.path}")
    private String reportTmpPath;

    @Value(value = "${report-tmp.export-path}")
    private String exportPath;

    /**
     * 分页列表查询
     *
     * @param userReports
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "user_reports-分页列表查询")
    @ApiOperation(value = "user_reports-分页列表查询", notes = "user_reports-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<UserReports>> queryPageList(UserReports userReports,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        QueryWrapper<UserReports> queryWrapper = QueryGenerator.initQueryWrapper(userReports, req.getParameterMap());
        Page<UserReports> page = new Page<UserReports>(pageNo, pageSize);
        IPage<UserReports> pageList = userReportsService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param userReportsPage
     * @return
     */
    @AutoLog(value = "user_reports-添加")
    @ApiOperation(value = "user_reports-添加", notes = "user_reports-添加")
    //@RequiresPermissions("userReports:user_reports:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody UserReportsPage userReportsPage) {
        UserReports userReports = new UserReports();
        BeanUtils.copyProperties(userReportsPage, userReports);
        userReports.setCreateDate(new Date());
        userReportsService.saveMain(userReports, userReportsPage.getUserReportsFieldList(), userReportsPage.getUserReportsRowList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param userReportsPage
     * @return
     */
    @AutoLog(value = "user_reports-编辑")
    @ApiOperation(value = "user_reports-编辑", notes = "user_reports-编辑")
    //@RequiresPermissions("userReports:user_reports:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody UserReportsPage userReportsPage) {
        UserReports userReports = new UserReports();
        BeanUtils.copyProperties(userReportsPage, userReports);
        userReports.setTableName("");//todo 编辑的时候清除对应的表名（可以做到真正发生改变了再清除）
        UserReports userReportsEntity = userReportsService.getById(userReports.getId());
        if (userReportsEntity == null) {
            return Result.error("未找到对应数据");
        }
        userReportsService.updateMain(userReports, userReportsPage.getUserReportsFieldList(), userReportsPage.getUserReportsRowList());
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "user_reports-通过id删除")
    @ApiOperation(value = "user_reports-通过id删除", notes = "user_reports-通过id删除")
    //@RequiresPermissions("userReports:user_reports:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        userReportsService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "user_reports-批量删除")
    @ApiOperation(value = "user_reports-批量删除", notes = "user_reports-批量删除")
    //@RequiresPermissions("userReports:user_reports:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.userReportsService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "user_reports-通过id查询")
    @ApiOperation(value = "user_reports-通过id查询", notes = "user_reports-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<UserReports> queryById(@RequestParam(name = "id", required = true) String id) {
        UserReports userReports = userReportsService.getById(id);
        if (userReports == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(userReports);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "字段定义通过主表ID查询")
    @ApiOperation(value = "字段定义主表ID查询", notes = "字段定义-通主表ID查询")
    @GetMapping(value = "/queryUserReportsFieldByMainId")
    public Result<List<UserReportsField>> queryUserReportsFieldListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<UserReportsField> userReportsFieldList = userReportsFieldService.selectByMainId(id);
        return Result.OK(userReportsFieldList);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "计算范围通过主表ID查询")
    @ApiOperation(value = "计算范围主表ID查询", notes = "计算范围-通主表ID查询")
    @GetMapping(value = "/queryUserReportsRowByMainId")
    public Result<List<UserReportsRow>> queryUserReportsRowListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<UserReportsRow> userReportsRowList = userReportsRowService.selectByMainId(id);
        return Result.OK(userReportsRowList);
    }

    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BuildReportParam buildReportParam) {
        QueryWrapper<BuildReportParam> queryWrapper = QueryGenerator.initQueryWrapper(buildReportParam, request.getParameterMap());
        Map<String, String> paramsMap = new HashMap<>();
        String calcDate = DateUtils.date2Str(buildReportParam.getCalcDate(), DateUtils.date_sdf.get());
        paramsMap.put("report_id", buildReportParam.getReportId().toString());
        paramsMap.put("calc_date", calcDate);
        UserReports userReports = userReportsService.getById(buildReportParam.getReportId());
        if (userReports == null) {
            throw new Error("未找到对应数据");
        }

        List<BuildReport> pageList = new ArrayList<BuildReport>();
        try {
            String url = zfserviceUrl + "/formula/calc_report";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                Map maps = (Map) object.get("data");
                for (Object map : maps.entrySet()) {
                    JSONObject detail = (JSONObject) ((Map.Entry) map).getValue();
                    for (Object mapDetail : detail.entrySet()) {
                        BuildReport vo = new BuildReport();
                        vo.setField(((Map.Entry) map).getKey().toString());
                        vo.setSlotName(((Map.Entry) mapDetail).getKey().toString());
                        vo.setFieldValue(((Map.Entry) mapDetail).getValue().toString());
                        pageList.add(vo);
                    }
                }
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    //	return Result.error(object.get("message").toString());
                    throw new Error(object.get("message").toString());
                } else {
                    //return Result.error("生成失败");
                    throw new Error("生成失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            //return Result.error("生成失败");
        }

        // Step.1 组装查询条件查询数据
//      QueryWrapper<UserReports> queryWrapper = QueryGenerator.initQueryWrapper(userReports, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//
//      //配置选中数据查询条件
//      String selections = request.getParameter("selections");
//      if(oConvertUtils.isNotEmpty(selections)) {
//         List<String> selectionList = Arrays.asList(selections.split(","));
//         queryWrapper.in("id",selectionList);
//      }
//      //Step.2 获取导出数据
//      List<UserReports> userReportsList = userReportsService.list(queryWrapper);

        // Step.3 组装pageList
//      List<BuildReport> pageList = new ArrayList<BuildReport>();
//      for (UserReports main : userReportsList) {
//		  BuildReport vo = new BuildReport();excel
//          BeanUtils.copyProperties(main, vo);
////          List<UserReportsField> userReportsFieldList = userReportsFieldService.selectByMainId(main.getId().toString());
////          vo.setUserReportsFieldList(userReportsFieldList);
////          List<UserReportsRow> userReportsRowList = userReportsRowService.selectByMainId(main.getId().toString());
////          vo.setUserReportsRowList(userReportsRowList);
//          pageList.add(vo);
//      }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "报告");
        mv.addObject(NormalExcelConstants.CLASS, BuildReport.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(userReports.getReportName(), "导出人:" + sysUser.getRealname(), userReports.getReportName()));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }


    /**
     * 导出excel
     *
     * @param request
     * @param
     */
    //@RequiresPermissions("userReports:user_reports:exportXls")
    @RequestMapping(value = "/exportXls2")
    @ResponseBody
    public void exportXls2(HttpServletRequest request, BuildReportParam buildReportParam, HttpServletResponse response) throws IOException {
        QueryWrapper<BuildReportParam> queryWrapper = QueryGenerator.initQueryWrapper(buildReportParam, request.getParameterMap());
        Map<String, String> paramsMap = new HashMap<>();
        String calcDate = DateUtils.date2Str(buildReportParam.getCalcDate(), DateUtils.date_sdf.get());
        paramsMap.put("report_id", buildReportParam.getReportId().toString());
        paramsMap.put("calc_date", calcDate);
        UserReports userReports = userReportsService.getById(buildReportParam.getReportId());
        if (userReports == null) {
            throw new Error("未找到对应数据");
        }
        List<Map<String, Object>> colList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> valList = new ArrayList<Map<String, Object>>();

        List<BuildReport> pageList = new ArrayList<BuildReport>();
        try {
            String url = zfserviceUrl + "/formula/calc_report";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                Map maps = (Map) object.get("data");
                for (Object map : maps.entrySet()) {
                    JSONObject detail = (JSONObject) ((Map.Entry) map).getValue();
                    for (Object mapDetail : detail.entrySet()) {
                        BuildReport vo = new BuildReport();
                        vo.setField(((Map.Entry) map).getKey().toString());
                        vo.setSlotName(((Map.Entry) mapDetail).getKey().toString());
                        vo.setFieldValue(((Map.Entry) mapDetail).getValue().toString());
                        pageList.add(vo);
                    }
                }

                int index = 1;
                for (Object map : maps.entrySet()) {
                    Map<String, Object> mapHead = new HashMap<String, Object>();
                    mapHead.put("column", ((Map.Entry) map).getKey());
                    mapHead.put("value", "t.vl_" + index);
                    colList.add(mapHead);
                    index++;
                }

                List<String> slotList = pageList.stream().map(BuildReport::getSlotName).distinct().collect(Collectors.toList());
                for (int i = slotList.size(); i-- > 0; ) {
                    Map<String, Object> map = getSlotMap(pageList, colList, slotList.get(i));
                    valList.add(map);
                }
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    //	return Result.error(object.get("message").toString());
                    throw new Error(object.get("message").toString());
                } else {
                    //return Result.error("生成失败");
                    throw new Error("生成失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            //return Result.error("生成失败");
        }

        // Step.1 组装查询条件查询数据
//      QueryWrapper<UserReports> queryWrapper = QueryGenerator.initQueryWrapper(userReports, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        // Resource resource = new ClassPathResource("/doc/report.xlsx");
        //this.getClass().getClassLoader().getResource("").getPath() + "doc/report.xlsx"
        //TemplateExportParams params = new TemplateExportParams(resource.getURL().getPath());
        TemplateExportParams params = new TemplateExportParams(reportTmpPath);


        Map<String, Object> value = new HashMap<String, Object>();
        value.put("title", userReports.getReportName());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        value.put("date", simpleDateFormat.format(new Date()));

        value.put("colList", colList);
        value.put("valList", valList);
        params.setColForEach(true);
        Workbook workbook = ExcelExportUtil.exportExcel(params, value);
        if (workbook != null) ;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(userReports.getReportName(), "UTF-8"));
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            try {
                throw new Exception(e.getMessage());
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    @NotNull
    private Map<String, Object> getSlotMap(List<BuildReport> pageList, List<Map<String, Object>> colList, String slot) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("slot", slot);
        for (int i = 0; i < colList.size(); i++) {
            Map<String, Object> col = colList.get(i);
            String field = col.get("column").toString();
            String fieldValue = pageList.stream().filter(o -> o.getSlotName().equals(slot) && o.getField().equals(field)).findAny().get().getFieldValue();
            String num = col.get("value").toString().replace("t.", "");
            map.put(num, fieldValue);
        }

        //map.put("vl_2", 4);
        return map;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("userReports:user_reports:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<UserReportsPage> list = ExcelImportUtil.importExcel(file.getInputStream(), UserReportsPage.class, params);
                for (UserReportsPage page : list) {
                    UserReports po = new UserReports();
                    BeanUtils.copyProperties(page, po);
                    userReportsService.saveMain(po, page.getUserReportsFieldList(), page.getUserReportsRowList());
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

    @ApiOperation(value = "reports 历史数据-分页列表查询", notes = "reports 历史数据-分页列表查询")
    @GetMapping(value = "/hisotryPageList")
    public Result<IPage<Map<String, Object>>> hisotryPageList(UserReports userReports,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              @RequestParam(name = "slotNo", defaultValue = "") String slotNo,
                                                              HttpServletRequest req) {
        QueryWrapper<UserReports> queryWrapper = QueryGenerator.initQueryWrapper(userReports, req.getParameterMap());
        Page<Map<String, Object>> pageList = new Page<>(pageNo, pageSize);
        UserReports userReportsModel = userReportsService.getById(userReports.getId());
        List<UserReportsField> userReportsFieldList = userReportsFieldService.selectByMainId(userReports.getId().toString());
        String beginDate = "";
        String endDate = "";
        if (req.getParameterMap().containsKey("createTime_begin") && req.getParameterMap().get("createTime_begin") != null && org.apache.commons.lang.StringUtils.isNotEmpty(req.getParameterMap().get("createTime_begin").toString())) {
            beginDate = req.getParameterMap().get("createTime_begin")[0];
            endDate = req.getParameterMap().get("createTime_end")[0];
        }
        if (req.getParameterMap().containsKey("slotNo") && req.getParameterMap().get("slotNo") != null) {
            slotNo = req.getParameterMap().get("slotNo")[0];
        }

        pageList = userReportsService.getTableQueryDate(userReportsModel.getTableName(), slotNo, beginDate, endDate, pageSize, pageNo);
        pageList.setTotal(userReportsService.getTableTotal(userReportsModel.getTableName(), slotNo, beginDate, endDate));
        Map fieldResult = new HashMap<>();
        fieldResult.put("userReportsFieldList", userReportsFieldList);
        pageList.getRecords().add(0, fieldResult);
        //}
        return Result.OK(pageList);
    }

    @AutoLog(value = "报表管理-生成报告")
    @ApiOperation(value = "报表管理-生成报告", notes = "报表管理-生成报告")
    @PostMapping(value = "/buildReport")
    public Result<Object> buildReport(@RequestBody BuildReportParam buildReportParam) {
        String reportId = buildReportParam.getReportId().toString();
        UserReports userReports = userReportsService.getById(reportId);
        if (userReports == null) {
            throw new Error("未找到对应报告数据");
        }
        Map<String, String> paramsMap = new HashMap<>();
        String calcDate = DateUtils.date2Str(buildReportParam.getCalcDate(), DateUtils.date_sdf.get());
        paramsMap.put("report_id", reportId);
        paramsMap.put("calc_date", calcDate);
        List<UserReportsField> userReportsFieldList = userReportsFieldService.selectByMainId(reportId);
        if (StringUtils.isNotEmpty(userReports.getTableName()) && Boolean.FALSE.equals(buildReportParam.getRebuild())) {
            List<Map<String, Object>> result = userReportsService.getTableByCalcDate(userReports.getTableName(), calcDate);
            if (result != null && result.size() > 0) {
                Map maps = new HashMap();
                maps.put("userReportsFieldList", userReportsFieldList);
                maps.put("existData", true);
                maps.put("result", result);
                String fileUrl = this.exportXls(userReports.getReportName(), maps, result, userReportsFieldList, calcDate);
                userReports.setUrl(fileUrl);
                this.userReportsService.updateById(userReports);
                return Result.OK(maps);
            }
        } else {
            for (int j = 1; j < userReportsFieldList.size() + 1; j++) {
                userReportsFieldList.get(j - 1).setTableColumn("vl_" + j);
            }
            userReportsFieldService.updateBatchById(userReportsFieldList);
            List<String> colums = userReportsFieldList.stream().map(o -> o.getTableColumn()).collect(Collectors.toList());
            //动态创建表
            String tableName = "tb_report_" + DateUtils.date2Str(new Date(), DateUtils.yyyymmddhhmmss.get());
            this.userReportsService.createTable(tableName, colums);
            userReports.setTableName(tableName);
            this.userReportsService.updateById(userReports);
        }
        try {
            String url = zfserviceUrl + "/formula/calc_report";
            JSONObject object = HttpClientUtil.sendGet(url, paramsMap);
            if (object.get("code") != null && Integer.parseInt(object.get("code").toString()) == 0) {
                // List<UserReportsField> userReportsFieldList = userReportsFieldService.selectByMainId(reportId);
                Map maps = (Map) object.get("data");
                userReportsFieldList = userReportsFieldList.stream().sorted(Comparator.comparing(UserReportsField::getOrderNo)).collect(Collectors.toList());
                this.buildTableDate(userReports, maps, userReportsFieldList, calcDate);
                String fileUrl = this.exportXls(userReports.getReportName(), maps, null, userReportsFieldList, calcDate);
                userReports.setUrl(fileUrl);
                this.userReportsService.updateById(userReports);
                maps.put("existData", false);
                maps.put("userReportsFieldList", userReportsFieldList);
                return Result.OK(maps);
            } else {
                if (object.containsKey("message") && object.get("message") != null) {
                    return Result.error(object.get("message").toString());
                } else {
                    return Result.error("生成失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return Result.error("生成失败");
        }
    }

    //生成表单数据
    public void buildTableDate(UserReports userReports, Map maps, List<UserReportsField> userReportsFieldList, String calcDate) {
        List<Map<String, Object>> colList = new ArrayList<Map<String, Object>>();
        List<Map<String, Object>> valList = new ArrayList<Map<String, Object>>();

        List<BuildReport> pageList = new ArrayList<>();
        for (Object map : maps.entrySet()) {
            JSONObject detail = (JSONObject) ((Map.Entry) map).getValue();
            for (Object mapDetail : detail.entrySet()) {
                BuildReport vo = new BuildReport();
                vo.setField(((Map.Entry) map).getKey().toString());
                vo.setSlotName(((Map.Entry) mapDetail).getKey().toString());
                vo.setFieldValue(((Map.Entry) mapDetail).getValue().toString());
                pageList.add(vo);
            }
        }

        for (int j = 1; j < userReportsFieldList.size() + 1; j++) {
            Map<String, Object> mapHead = new HashMap<String, Object>();
            mapHead.put("column", userReportsFieldList.get(j - 1).getFieldName());
            mapHead.put("value", "t.vl_" + j);
            colList.add(mapHead);
        }

        List<String> slotList = pageList.stream().map(BuildReport::getSlotName).distinct().sorted().collect(Collectors.toList());
        for (int i = 0; i < slotList.size(); i++) {
            Map<String, Object> map = getSlotMap(pageList, colList, slotList.get(i));
            map.put("calc_date", calcDate);
            // map.put("id", UUID.randomUUID().toString().replaceAll("-", ""));
            valList.add(map);
            this.userReportsService.addTableRow(userReports.getTableName(), map);
        }
    }

    public String exportXls(String reportName, Map maps, List<Map<String, Object>> result, List<UserReportsField> userReportsFieldList, String calcDate) {
        List<Map<String, Object>> colList = new ArrayList<>();
        List<Map<String, Object>> valList = new ArrayList<>();
        if (result != null && result.size() > 0) {//已存在对应表数据
            for (int j = 1; j < userReportsFieldList.size() + 1; j++) {
                Map<String, Object> mapHead = new HashMap<>();
                mapHead.put("column", userReportsFieldList.get(j - 1).getFieldName());
                mapHead.put("value", "t." + userReportsFieldList.get(j - 1).getTableColumn());
                colList.add(mapHead);
            }
            valList = result;
        } else {
            List<BuildReport> pageList = new ArrayList<>();
            for (Object map : maps.entrySet()) {
                JSONObject detail = (JSONObject) ((Map.Entry) map).getValue();
                for (Object mapDetail : detail.entrySet()) {
                    BuildReport vo = new BuildReport();
                    vo.setField(((Map.Entry) map).getKey().toString());
                    vo.setSlotName(((Map.Entry) mapDetail).getKey().toString());
                    vo.setFieldValue(((Map.Entry) mapDetail).getValue().toString());
                    pageList.add(vo);
                }
            }

//        int index = 1;
//        for (Object map : maps.entrySet()) {
//            Map<String, Object> mapHead = new HashMap<String, Object>();
//            mapHead.put("column", ((Map.Entry) map).getKey());
//            mapHead.put("value", "t.vl_" + index);
//            colList.add(mapHead);
//            index++;
//        }
            for (int j = 1; j < userReportsFieldList.size() + 1; j++) {
                Map<String, Object> mapHead = new HashMap<String, Object>();
                mapHead.put("column", userReportsFieldList.get(j - 1).getFieldName());
                mapHead.put("value", "t.vl_" + j);
                colList.add(mapHead);
            }

            List<String> slotList = pageList.stream().map(BuildReport::getSlotName).distinct().sorted().collect(Collectors.toList());
            for (int i = 0; i < slotList.size(); i++) {
                Map<String, Object> map = getSlotMap(pageList, colList, slotList.get(i));
                valList.add(map);
            }
//        for (int i = slotList.size(); i-- > 0; ) {
//            Map<String, Object> map = getSlotMap(pageList, colList, slotList.get(i));
//            valList.add(map);
//        }
        }
        TemplateExportParams params = new TemplateExportParams(reportTmpPath);
        Map<String, Object> value = new HashMap<String, Object>();
        value.put("title", reportName);
        value.put("date", calcDate);

        value.put("colList", colList);
        value.put("valList", valList);
        params.setColForEach(true);
        Workbook workbook = ExcelExportUtil.exportExcel(params, value);
        if (workbook != null) ;
        String fileUrl = "";
        try {
            Date d = new Date();
            String fileName = reportName + DateUtils.yyyymmddhhmmss.get().format(d);
            String ctxPath = exportPath;
            File file = new File(ctxPath);
            if (!file.exists()) {
                // 创建文件根目录
                file.mkdirs();
            }
            fileUrl = fileName + ".xls";
            FileOutputStream fileOutputStream = new FileOutputStream(file.getPath() + "/" + fileName + ".xls");
            //写入输出流
            workbook.write(fileOutputStream);

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关流
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return fileUrl;
    }

    @ApiOperation(value = "reports 历史数据-分页列表查询", notes = "reports 历史数据-分页列表查询")
    @GetMapping(value = "/hisotryDays")
    public Result<List<String>> hisotryDays(UserReports userReports, @RequestParam(name = "slotNo", defaultValue = "") String slotNo,
                                            HttpServletRequest req) {
        List<String> dateList;
        UserReports userReportsModel = userReportsService.getById(userReports.getId());
        String beginDate = "";
        String endDate = "";
        if (req.getParameterMap().containsKey("createTime_begin") && req.getParameterMap().get("createTime_begin") != null && org.apache.commons.lang.StringUtils.isNotEmpty(req.getParameterMap().get("createTime_begin").toString())) {
            beginDate = req.getParameterMap().get("createTime_begin")[0];
            endDate = req.getParameterMap().get("createTime_end")[0];
        }
        if (req.getParameterMap().containsKey("slotNo") && req.getParameterMap().get("slotNo") != null) {
            slotNo = req.getParameterMap().get("slotNo")[0];
        }

        dateList = userReportsService.getDateList(userReportsModel.getTableName(), slotNo, beginDate, endDate);
        List<LocalDate> dates = getDatesBetween(LocalDate.parse(beginDate), LocalDate.parse(endDate));
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); //定义时间格式
        List<String> dateUntreated = new ArrayList<>();
        dates.forEach(item -> {
           if(!dateList.contains(item.format(dtf))){
               dateUntreated.add(item.format(dtf));
           }
        });
        return Result.OK(dateUntreated);
    }

    public List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
        List<LocalDate> dates = new ArrayList<>();
        long numDays = ChronoUnit.DAYS.between(startDate, endDate);
        for (int i = 0; i <= numDays; i++) {
            dates.add(startDate.plusDays(i));
        }
        return dates;
    }
}
